package com.example.asa;

import java.io.IOException;
import java.sql.*;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 事件实体类


@WebServlet("/home")
public class HomeServlet extends HttpServlet {

    public void log(String message) {
        System.out.println("[HomeServlet] " + new Date() + " - " + message);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        log("==== 请求开始 ====");

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 1. 获取数据库连接
            try {
                conn =DatabaseUtil.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }


            // 2. 执行查询（使用正确的字段名 publish_time）
            String sql = "SELECT title, content, severity, publish_time FROM alerts ORDER BY publish_time DESC LIMIT 1";

            try {
                pstmt = conn.prepareStatement(sql);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                rs = pstmt.executeQuery();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }


            ResultSetMetaData metaData = null;
            try {
                metaData = rs.getMetaData();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            int columnCount = 0;
            try {
                columnCount = metaData.getColumnCount();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            log("结果集列数: " + columnCount);
            for (int i = 1; i <= columnCount; i++) {
                try {
                    log("列 " + i + ": " + metaData.getColumnName(i));
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            // 4. 处理结果
            String type = null;
            String location = null;
            String status = null;
            String publishTime = null;
            while (true) {
                try {
                    if (!rs.next()) break;
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                try {
                    type = rs.getString("title");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                try {
                    location = rs.getString("content");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                try {
                    status = rs.getString("severity");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                try {
                    publishTime = rs.getString("publish_time");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            request.setAttribute("type", type);
            request.setAttribute("location", location);
            request.setAttribute("status", status);
            request.setAttribute("publishTime", publishTime);


            ResultSet rs1 = null;
            ResultSet rs2 = null;
            ResultSet rs3 = null;

            try {
                conn =DatabaseUtil.getConnection();

                // 统计当前预警数量（status = '预警'）
                String sqlWarning = "SELECT COUNT(*) AS warningCount FROM alerts WHERE severity = '高'";
                pstmt = conn.prepareStatement(sqlWarning);
                rs1 = pstmt.executeQuery();
                int warningCount = 0;
                if (rs1.next()) {
                    warningCount = rs1.getInt("warningCount");
                }
                while (rs1.next()) {
                    warningCount = rs1.getInt("warningCount");

                }

                // 统计响应中事件数量（status = '响应中'）
                String sqlResponding = "SELECT COUNT(*) AS respondingCount FROM alerts WHERE severity = '中'";
                pstmt = conn.prepareStatement(sqlResponding);
                rs2 = pstmt.executeQuery();
                int respondingCount = 0;
                if (rs2.next()) {
                    respondingCount = rs2.getInt("respondingCount");
                }
                while (rs2.next()) {
                    respondingCount = rs2.getInt("respondingCount");

                }

                // 统计已解决事件数量（status = '已解决'）
                String sqlResolved = "SELECT COUNT(*) AS resolvedCount FROM alerts WHERE severity = '低'";
                pstmt = conn.prepareStatement(sqlResolved);
                rs3 = pstmt.executeQuery();
                int resolvedCount = 0;
                if (rs3.next()) {
                    resolvedCount = rs3.getInt("resolvedCount");
                }
                while (rs3.next()) {
                    resolvedCount = rs3.getInt("resolvedCount");

                }

                // 将统计结果放入 request 属性中
                request.setAttribute("warningCount", warningCount);
                request.setAttribute("respondingCount", respondingCount);
                request.setAttribute("resolvedCount", resolvedCount);


            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().print("加载统计数据失败：" + e.getMessage());
            } finally {
                DatabaseUtil.close(conn, pstmt, rs);
            }
            // 6. 转发请求
            RequestDispatcher dispatcher = request.getRequestDispatcher("shouye.jsp");
            log("准备转发到shouye.jsp");
            dispatcher.forward(request, response);
            log("转发完成");


        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}